package main.social.web;

import java.text.*;

import javax.servlet.http.*;

import main.social.entities.Accounts;
import main.social.service.AccountService;

import org.apache.commons.logging.*;
import org.springframework.beans.propertyeditors.*;
import org.springframework.web.bind.*;
import org.springframework.web.servlet.*;
import org.springframework.web.servlet.mvc.*;
import org.springframework.web.servlet.view.*;
import javax.servlet.ServletException;
import org.springframework.validation.BindException;


public class AccountFormController extends SimpleFormController {

    protected final Log logger = LogFactory.getLog(getClass());
    private AccountService accountService;

    public AccountService getAccountService() {

        return accountService;
    }

    public void setAccountService(AccountService accountService) {

        this.accountService = accountService;
    }


    public ModelAndView onSubmit(HttpServletRequest request,
                                 HttpServletResponse response, Object cmd,
                                 BindException errors) throws Exception {

        logger.debug(
                "Entering MyObjectFormController handleRequest method ....");
        Accounts account = (Accounts) cmd;
        if (null != request.getParameter("delete")) {
            System.out.println("[Delete] button pressed ... ");
            accountService.removeAccount(account);
        } else if (null != request.getParameter("update")) {
            accountService.updateAccount(account);
            System.out.println("[Update] button pressed ... ");
        } else if (null != request.getParameter("add")) {
            accountService.insertAccount(account);
            System.out.println("[Add] button pressed ... ");
        }
        return new ModelAndView(new RedirectView(getSuccessView()));
    }


    protected Object formBackingObject(HttpServletRequest request) throws
            ServletException {
        String id = request.getParameter("id");
        if (null != id && !id.equals("")) {
            return accountService.findAccountById(Integer.parseInt(id));
        }
        return Accounts.newInstance();
    }


}
